package com.zpkj.portal.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zpkj.portal.third.ios.TradeCheck;  

/**
 * IOS支付验证工具类
 * 服务器找苹果验证时各返回码的意义:
 * 0 验证成功
 * 21000 App Store不能读取你提供的JSON对象
 * 21002 receipt-data域的数据有问题
 * 21003 receipt无法通过验证
 * 21004 提供的shared secret不匹配你账号中的shared secret
 * 21005 receipt服务器当前不可用
 * 21006 receipt合法，但是订阅已过期。服务器接收到这个状态码时，receipt数据仍然会解码并一起发送
 * 21007 receipt是Sandbox receipt，但却发送至生产系统的验证服务
 * 21008 receipt是生产receipt，但却发送至Sandbox环境的验证服务
 * @author xc
 * 2016年5月6日 上午10:48:35
 */
public class IosVerify {
    
	private static Logger logger = LoggerFactory.getLogger(IosVerify.class);
	
    //ios沙盒验证地址
    public static final String url_sandbox="https://sandbox.itunes.apple.com/verifyReceipt"; 
    //ios正式验证地址
    public static final String url_verify="https://buy.itunes.apple.com/verifyReceipt";  
      
//    public static void main(String[] args) {
//    	String receipt = "MIIT1wYJKoZIhvcNAQcCoIITyDCCE8QCAQExCzAJBgUrDgMCGgUAMIIDeAYJKoZIhvcNAQcBoIIDaQSCA2UxggNhMAoCARQCAQEEAgwAMAsCAQMCAQEEAwwBNTALAgEOAgEBBAMCAXgwCwIBEwIBAQQDDAE1MAsCARkCAQEEAwIBAzANAgEKAgEBBAUWAzE3KzANAgENAgEBBAUCAwFgvjAOAgEBAgEBBAYCBEItY\\/AwDgIBCQIBAQQGAgRQMjQ0MA4CAQsCAQEEBgIEBwubnTAOAgEQAgEBBAYCBDC2eFEwEAIBDwIBAQQIAgYgwtQvPUEwFAIBAAIBAQQMDApQcm9kdWN0aW9uMBgCAQQCAQIEEKNiZCb1PYe4m1sH9IgaNbAwHAIBBQIBAQQUtD2eV8Fdrb\\/1Y84ik+0R+usFGMM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wbeZVmZyGrUABI1OIUt5JrqLIeZ\\/5YkQaUZjg\\/YKpUzlK\\/k5JPywcwCCQ==";
//    	System.out.println("**********"+receipt);
//		System.out.println(verifyReceipt(false,receipt.trim()));//可用
//    }
    
    //校验ios的票据
    public static TradeCheck verifyReceipt(boolean isSandBox, String receipt) {  
    	String url = url_verify;
    	if( isSandBox ){
    		url = url_sandbox;
    	}
        try {  
            HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();    
            connection.setRequestMethod("POST");    
            connection.setDoOutput(true);    
            connection.setAllowUserInteraction(false);   
            PrintStream ps = new PrintStream(connection.getOutputStream());    
            ps.print("{\"receipt-data\": \"" + receipt + "\"}");    
            ps.close();    
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));    
            String str;    
            StringBuffer sb = new StringBuffer();    
            while ((str = br.readLine()) != null) {    
                sb.append(str);      
            }    
            br.close();    
            String resultStr = sb.toString(); 
            logger.info("*****苹果验证的返回:::"+resultStr+"*****");
            TradeCheck tc = JsonUtils.fromJson(resultStr, TradeCheck.class);
//            JSONObject result = JSONObject.parseObject(resultStr);  
            if (tc != null && tc.getStatus() == 21007) {  
                return verifyReceipt( true, receipt );  
            }  
            return tc;  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    } 
    
}
